import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

const request = axios.create({
  baseURL: '',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 标记是否正在刷新token
let isRefreshing = false
// 存储等待token刷新的请求
let requests = []

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === '0000' && res.info === '调用成功') {
      return res
    }
    
    ElMessage.error(res.info || '请求失败')
    return Promise.reject(new Error(res.info || '请求失败'))
  },
  error => {
    if (error.response?.status === 401) {
      const currentPath = router.currentRoute.value.fullPath
      
      if (currentPath !== '/login') {
        ElMessage.error('登录已过期，请重新登录')
        // 保存当前路由
        localStorage.setItem('redirect', currentPath)
        // 使用路由导航而不是直接刷新页面
        router.push('/login')
      }
    } else {
      ElMessage.error(error.message || '请求失败')
    }
    return Promise.reject(error)
  }
)

export default request 